package com.spx.chapter07;

import com.spx.chapter05.pojo.Event;
import com.spx.util.ClickSource;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.sql.Timestamp;


/**
 * create by undeRdoG on  2022-05-03  15:15
 * 凡心所向，素履以往，生如逆旅，一苇以航。
 */
public class ProcessingTimeTimerTest {

    /**
    *   只有 KeyedStream才可以注册定时器，普通的DataStream注册定时器会直接报错
    * */
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        SingleOutputStreamOperator<Event> stream = env.addSource(new ClickSource());

        stream.keyBy(data -> data.user)
                // 使用KeyedProcessFunction
                .process(new KeyedProcessFunction<String, Event, String>() {
                    @Override
                    public void processElement(Event value, Context ctx, Collector<String> out) throws Exception {
                        // 获取当前数据的时间戳
                        Long currentTimestamp = ctx.timestamp();

                        // 获取当前的处理时间
                        long currentProcessingTime = ctx.timerService().currentProcessingTime();

                        out.collect(ctx.getCurrentKey() + " 数据到达，到达时间" + new Timestamp(currentProcessingTime));

                        // 注册一个10s后的定时器
                        ctx.timerService().registerProcessingTimeTimer(currentProcessingTime + 10 * 1000);

                    }


                    @Override
                    public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {

                        out.collect(ctx.getCurrentKey() + " 定时器触发，触发时间为：" + new Timestamp(timestamp));

                    }
                }).print();


        env.execute();

    }
}
